package com.software.twinmanager.tcp;

import com.software.twinmanager.controller.MessageReceiver;

import java.io.IOException;
import java.net.Socket;

public class TCPConnection{
    private Socket socket = null;

    public TCPConnection(String address, int port, MessageReceiver server) throws IOException{
        socket = new Socket(address, port);
        socket.setKeepAlive(true);
        new ReceiveMessageThread(socket.getInputStream(), server).start();
    }

    public void startBelt(byte num, byte speed) throws IOException {
        byte[] command = new byte[]{1, num, speed, 0, 0, 0, 0, 0};
        socket.getOutputStream().write(command);
    }

    public void stopBelt(byte num) throws IOException {
        byte[] command = new byte[]{2, num, 0, 0, 0, 0, 0, 0};

        socket.getOutputStream().write(command);
    }

    public void push(byte num, byte hold) throws IOException {
        byte[] command = new byte[]{3, num, 1, hold, 0, 0, 0, 0};

        socket.getOutputStream().write(command);
    }

    public void getCurrentInfo() throws IOException {
        byte[] command = new byte[]{4, 0, 0, 0, 0, 0, 0, 0};

        socket.getOutputStream().write(command);
    }

    public boolean isClosed() {
        return !socket.isConnected() || socket.isClosed();
    }

    public void close() throws IOException {
        this.socket.close();
    }
}

